<?php
/**
 * Created by JetBrains PhpStorm.
 * User: shaoshuai
 * Date: 11-10-2
 * Time: PM9:22
 */

/**
 * 通过文章ID获取存储路径
 * 
 * @param string $id 文章ID
 * @return string 文章数据存储路径
 */
function getPath($id)
{
    return PB_ROOT . '/admin/data/posts/' . md5($id) . '.json';
}

/**
 * Fetch all posts order by create time asc
 *
 * @return array
 */
function getPosts()
{
    $index = getPostIndex();
    $posts = array();
    foreach ($index as $id) {
        array_push($posts, getPostById($id));
    }
    return $posts;
}

function getPostIndex()
{
    return json_decode(file_get_contents(PB_ROOT_DATA . '/index.json'), true);
}

function savePosts($posts)
{
    return file_put_contents(PB_ROOT_DATA . '/index.json', json_encode($posts));
}

function addPost($post)
{
    $index = getPostIndex();
    if (in_array($post['url'], $index)) {
        return false;
    } else {
        array_push($index, $post['url']);
        if (!file_put_contents(getPath($post['url']), json_encode($post))) {
            exit('can not write /data/posts/');
        }
        return savePosts($index);
    }
}

function getVerify()
{
    return json_decode(file_get_contents(PB_ROOT_DATA . '/verify.json'), true);
}

function saveVerify($verify)
{
    return file_put_contents(PB_ROOT_DATA . '/verify.json', json_encode($verify));
}

function addVerify($comment)
{
    $verify = getVerify();
    array_push($verify, $comment);
    mail(MAILTO, 'verify', print_r($comment, true));
    return saveVerify($verify);
}

function getRelatedPosts($id)
{
    $post = getPostById($id);
    $tags = $post['tag'];
    $allTags = getTags();

    $relatedPosts = array();
    foreach ($tags as $tag) {
        $r = $allTags[$tag];
        $relatedPosts = array_merge($relatedPosts, $r['posts']);
    }
    $relatedPosts = array_values(array_unique($relatedPosts));
    if (in_array($id, $relatedPosts)) {
        unset($relatedPosts[array_search($id, $relatedPosts)]);
    }
    return array_slice(array_reverse(array_values($relatedPosts)), 0, 5);
}

function getLinks()
{
    return json_decode(file_get_contents(PB_ROOT_DATA . '/links.json'), true);
}

function saveLinks($links)
{
    return file_put_contents(PB_ROOT_DATA . '/links.json', json_encode($links));
}

function getNavs()
{
    return json_decode(file_get_contents(PB_ROOT_DATA . '/navs.json'), true);
}

function saveNavs($navs)
{
    return file_put_contents(PB_ROOT_DATA . '/navs.json', json_encode($navs));
}

function getCategorys()
{
    return json_decode(file_get_contents(PB_ROOT_DATA . '/categorys.json'), true);
}

function saveCategorys($categorys)
{
    return file_put_contents(PB_ROOT_DATA . '/categorys.json', json_encode($categorys));
}

function addPostToCategory($postId, $categoryId)
{
    $categorys = getCategorys();
    array_push($categorys[$categoryId]['posts'], $postId);
    return saveCategorys($categorys);
}

function getCategoryNameById($id)
{
    $categorys = getCategorys();
    $ret = '';
    if ($categorys[$id]) {
        $ret = $categorys[$id]['name'];
    }
    return $ret;
}

function getTags()
{
    return json_decode(file_get_contents(PB_ROOT_DATA . '/tags.json'), true);
}

function saveTags($tags)
{
    return file_put_contents(PB_ROOT_DATA . '/tags.json', json_encode($tags));
}

function addTag($tagName)
{
    $oldTags = getTags();
    if (!$oldTags[$tagName]) {
        $oldTags[$tagName] = array('href' => SITE_URL . '/tag/' . $tagName . '.html', 'text' => $tagName, 'posts' => array());
        return savePosts($oldTags);
    } else {
        return true;
    }
}

/**
 * 更新现有Tag对应的Posts
 *
 * @param string $url
 * @param array $tags
 * @return boolean
 */
function updateTags($url, $tags)
{
    $oldTags = getTags();
    foreach ($tags as $tag) {
        if ($oldTags[$tag]) {
            if (!in_array($url, $oldTags[$tag]['posts'])) {
                array_push($oldTags[$tag]['posts'], $url);
            }
        } else {
            $oldTags[$tag] = array('name' => $tag, 'posts' => array($url));
        }
    }
    return saveTags($oldTags);
}

function getPostById($id)
{
    $contents = file_get_contents(getPath($id));
    $ret = false;
    if ($contents) {
        $ret = json_decode(file_get_contents(getPath($id)), true);
    }
    return $ret;
}

function updatePostById($id, $post)
{
    $ret = false;
    if ($post) {
        $ret = file_put_contents(getPath($id), json_encode($post));
    }
    return $ret;
}

function compilePostById($id, $data = null)
{
    if (!$data) {
        $post = getPostById($id);
    } else {
        $post = $data;
    }

    ob_start();
    include PB_ROOT_ADMIN . '/tpl/article.php';
    $content = ob_get_clean();
    file_put_contents(PB_HTML_POST . '/' . $post['url'] . '.html', $content);
}

/**
 * @return mixed
 */
function getSettings()
{
    return json_decode(file_get_contents(PB_ROOT_DATA . '/settings.json'), true);
}

function saveSettings($settings)
{
    return file_put_contents(PB_ROOT_DATA . '/settings.json', json_encode($settings));
}

/**
 * check if each key in list submitted
 *
 * @param $request
 * @param array $list
 * @return boolean
 */
function checkIsset($request, $list = array())
{
    $ret = true;
    foreach ($list as $key) {
        if (!isset($request[$key])) {
            $ret = false;
            break;
        }
    }
    return $ret;
}

function compilePaging($config)
{
    echo "Compile paging start ...\n";

    $posts = $config['posts'];
    $title = $config['title'];
    $filename = $config['filename'];

    $settings = getSettings();

    $index = array_reverse($posts);
    $postCount = count($index);
    $pageSize = intval($settings['page_size']);
    echo $pageSize, ' posts per page', "\n";

    if ($postCount % $pageSize == 0) {
        $pageCount = intval($postCount / $pageSize);
    } else {
        $pageCount = intval($postCount / $pageSize) + 1;
    }

    echo "There will be $pageCount page(s).\n";
    for ($i = 0; $i < $pageCount; $i++) {
        $page = $i + 1;
        $data = array();
        for ($start = $i * $pageSize, $end = ($i + 1) * $pageSize; $start < $end && $start < $postCount; $start++) {
            //echo $start, "\n", $end, "\n";
            array_push($data, $index[$start]);
        }
        compilePage(array('page' => $page, 'data' => $data, 'page_count' => $pageCount, 'title' => $title, 'filename' => $filename, 'dir' => $config['dir'], 'document_root' => $config['document_root']));
    }
    echo "\n";
}

function compilePage($config)
{
    $page = $config['page'];
    $data = $config['data'];
    $pageCount = $config['page_count'];
    $title = $config['title'];
    $filename = $config['filename'];
    $dir = $config['dir'];
    $documentRoot = $config['document_root']; //which url access the compiled html files

    if ($page != 1) {
        $current = $filename . '_' . $page;
    } else {
        $current = $filename;
    }
    $prevPage = false;
    $nextPage = false;
    $prev = $page - 1;
    $next = $page + 1;

    if ($prev == 1) {
        $prevPage = $filename;
    } elseif ($prev > 1) {
        $prevPage = $filename . '_' . $prev;
    }
    if ($next <= $pageCount) {
        $nextPage = $filename . '_' . $next;
    }
    $posts = $data;

    echo "start compile page $page ($current), total $pageCount pages\n";
    if ($prevPage) {
        echo "\t$current's prev is $prevPage\n";
    } else {
        echo "\t$current has no prev page\n";
    }
    if ($nextPage) {
        echo "\t$current's next is $nextPage\n";
    } else {
        echo "\t$current has no next page\n";
    }

    ob_start();
    include PB_ROOT_ADMIN . '/tpl/index.php';
    $content = ob_get_clean();
    file_put_contents($dir . '/' . $current . '.html', $content);
    echo $dir, '/', $current, '.html', "\n";
    echo "\n";
}

function compileIndex()
{
    $posts = getPosts();
    $settings = getSettings();
    $index = array_reverse(array_values($posts));
    $postCount = count($index);
    $pageSize = intval($settings['page_size']);

    if ($postCount % $pageSize == 0) {
        $pageCount = intval($postCount / $pageSize);
    } else {
        $pageCount = intval($postCount / $pageSize) + 1;
    }

    for ($i = 0; $i < $pageCount; $i++) {
        $page = $i + 1;
        $data = array();
        for ($start = $i * $pageSize, $end = ($i + 1) * $pageSize; $start < $end && $start < $postCount; $start++) {
            array_push($data, $index[$start]);
        }
        compileIndexFile($page, $data, $pageCount);
    }
}

function compileIndexFile($page, $data, $pageCount = 1)
{
    if ($page == 1) {
        $filename = 'index';
    } else {
        $filename = 'index_' . $page;
    }
    $prevPage = false;
    $nextPage = false;
    $prev = $page - 1;
    $next = $page + 1;
    if ($prev == 1) {
        $prevPage = 'index';
    } elseif ($prev > 1) {
        $prevPage = 'index_' . $prev;
    }
    if ($next <= $pageCount) {
        $nextPage = 'index_' . $next;
    }
    $posts = $data;

    $title = '主页';
    ob_start();
    include PB_ROOT_ADMIN . '/tpl/index.php';
    $content = ob_get_clean();
    file_put_contents(PB_ROOT . '/' . $filename . '.html', $content);
}

$settings = getSettings();
define('AUTHOR', $settings['author']);
define('SITE_TITLE', $settings['title']);
define('SITE_URL', $settings['base']);
define('MAILTO', $settings['mailto']);
define('VERIFY_URL', $settings['base'] . '/action/verify.action.php?vid=');
//define('VERIFY_URL', 'http://localhost:10088/showframework/paperblog/action/verify.action.php?vid=');

/**
 * 获取全局配置
 *
 * @return array 全局配置数组
 */
function config()
{
    return include PB_ROOT_ADMIN . 'config.php';
}

function isIpAllow()
{
    $ip = $_SERVER['REMOTE_ADDR'];
    $config = config();
    $ips = $config['ip'];
    $ret = false;
    foreach ($ips as $i) {
        if ($i == $ip) {
            $ret = true;
            break;
        }
    }
    return $ret;
}